#include "device_communication.grpc.pb.h"
#include "server_base.h"
#include <atomic>
#include <csignal>
#ifdef _WIN32
#include <tchar.h>
#include <windows.h>
#elif __APPLE__
#include <sys/utsname.h>
#else // Linux
#include <sys/utsname.h>
#endif

class Server : public ServerBase {
public:
  Server() = default;
  ~Server() override = default;

protected:
  void GetPlatformInfo(std::string &platform, std::string &deviceModel,
                       std::string &systemVersion) override {
    // 获取设备型号和系统版本（跨平台实现）
#ifdef _WIN32

    // Windows系统信息获取
    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    GetVersionEx((OSVERSIONINFO *)&osvi);

    std::stringstream ss;
    ss << "Windows " << osvi.dwMajorVersion << "." << osvi.dwMinorVersion;
    if (osvi.wProductType == VER_NT_WORKSTATION) {
      ss << " (Workstation)";
    } else {
      ss << " (Server)";
    }
    platform = "Windows" systemVersion = ss.str();
    deviceModel = "x86_64"; // 简化处理，实际可通过CPUID获取
#elif __APPLE__
    // macOS系统信息获取
    struct utsname unameData;
    uname(&unameData);
    platform = std::string(unameData.sysname);
    systemVersion = std::string(unameData.version);
    deviceModel = std::string(unameData.machine); // 如x86_64或arm64

#else
    // Linux系统信息获取
    struct utsname unameData;
    uname(&unameData);
    platform = std::string(unameData.sysname);
    systemVersion = std::string(unameData.release);
    deviceModel = std::string(unameData.machine); // 如x86_64
#endif

    std::cout << "[Server] Platform info: " << platform
              << ", Model: " << deviceModel << ", Version: " << systemVersion
              << std::endl;
  }
};

std::atomic<bool> gShouldExit = false;

void SignalHandler(int signal) {
  if (signal == SIGINT || signal == SIGTERM) {
    std::cout << "Received signal " << signal << ", Stopping server..."
              << std::endl;
    gShouldExit = true;
  }
}

int main(int argc, char **argv) {
  signal(SIGINT, SignalHandler);
  signal(SIGTERM, SignalHandler);

  std::string port = "50051";
  if (argc > 1) {
    port = argv[1];
  }

  Server server;
  if (!server.StartServer(port)) {
    std::cerr << "Failed to start server" << std::endl;
    return 1;
  }

  std::cout << "gRPC server running on port " << port << std::endl;
  std::cout << "Press Ctrl+C to stop..." << std::endl;

  while (!gShouldExit) {
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
  server.StopServer();
  std::cout << "Server stopped successfully" << std::endl;
  return 0;
}